package com.zhz.redisdemo2.controller;


import com.zhz.redisdemo2.entity.User;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@RequestMapping("/redis")
@RestController
public class RedisController {

    @Resource
    private RedisTemplate redisTemplate;

    @RequestMapping("set")
    public boolean redisSet(String key,String value){
        try {
            redisTemplate.opsForValue().set(key,value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @RequestMapping("get")
    public Object redisGet(String key){
       return redisTemplate.opsForValue().get(key);
    }

    @RequestMapping("expire")
    public boolean expire(String key){
        return redisTemplate.expire(key,60,TimeUnit.SECONDS);
    }

    private int id =1;
    @RequestMapping("setobj")
    public boolean redisSetObject(String key){
        User user = new User();
        user.setId(Long.valueOf(id));
        user.setName("zhangsan"+id);
        user.setGuid(String.valueOf(id));
        user.setAge(String.valueOf(20));
        user.setCreateTime(new Date());
        try {
            redisTemplate.opsForValue().set(key,user);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
